/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ACER
 */
public class DatabaseConnection {
// Private Variables
    private Connection cn = null;
    private String ServerName = "";
    private String Port = "";
    private String Username = "";
    private String Password = "";
    private String Database = "";
    
    public DatabaseConnection() {
    }
// Constructor DatabaseConnection

    public DatabaseConnection(String ServerName, String Port, String Username, String Password, String Database) {
        this.ServerName = ServerName;
        this.Port = Port;
        this.Username = Username;
        this.Password = Password;
        this.Database = Database;
    }
/* Method LoadConfig read file config.txt.
 * Input: config.txt.
 * Output: 0 Load config successful
           1 File config.txt !exit
 *         2 File config.txt empty.
 *
 */
    public boolean LoadConfig() {
        String str = "";
        String[] str_split = null;
        File f = new File("config.txt");
        if(!f.exists())
          return false;
        try {
            BufferedReader br = new BufferedReader(new FileReader(f));
            while ((str = br.readLine()) != null) {
                str_split = str.split(":");
            }
            if(str_split == null){
                return false;
            }
        } catch (IOException ex) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
            //System.out.println(ex.getMessage());
        }
        this.ServerName = str_split[0];
        this.Port = str_split[1];
        this.Username = str_split[2];
        this.Password = str_split[3];
        this.Database = str_split[4];
        return true;
    }
    public Connection Connect() throws Exception
    {
        String str="jdbc:sqlserver://";
        str+=this.ServerName+":"+this.Port+";user="+this.Username;
        str+=";password="+this.Password+";database="+this.Database;   
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        cn = DriverManager.getConnection(str);  
        return cn;
    }
}
